package com.aaa.config;

import com.aaa.dao.UsersDao;
import com.aaa.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建UserDetailsService的接口实现类1
 * 这个实现类需要实现的唯一方法就是 根据secirutg 提供的用户名
 * 去数据库中去查询 密码 交给securitg
 *
 */
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UsersDao usersDao;
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据username 去数据库查询密码
        Users user = usersDao.findByUsername(username);
        if (user==null){
            //抛出一个异常
            throw new UsernameNotFoundException("用户名存在");
        }

//        //654321
//        String password =  user.getPassword();
//         //声明一个空的权限集合
//        List< GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
//        //去数据库把用户的权限信息查出来  往authorities这个里面放
//        authorities.add(new SimpleGrantedAuthority("user"));
//        authorities.add(new SimpleGrantedAuthority("role"));
//
//        UserDetails userDetails = new User(username,password,authorities);
        //把用户的权限信息查询出来
        //把用户的权限信息也查询出来放到session中
        //List<String> permits = menuService.ListUserPermits(user.getUid());
        List< GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        /*for (String permit :permits){
            authorities.add(new SimpleGrantedAuthority(permit));
        }*/
        //去数据库把用户的权限信息查出来  往authorities这个里面放
        user.setAuthorities(authorities);
        return  user;
    }
}
